/**
 * Copyright (c) 2009-2016, LarryKoo 老古 (gumutianqi@gmail.com)
 * <p/>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p/>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p/>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jfinal.ext.plugin.quartz;

import java.sql.Connection;
import java.sql.SQLException;

import org.quartz.utils.ConnectionProvider;

import com.alibaba.druid.filter.stat.StatFilter;
import com.alibaba.druid.wall.WallFilter;
import com.jfinal.ext.plugin.druid.DruidEncryptPlugin;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;

/**
 * @ClassName: QuartzConnectionProvider
 * @Description：自定义的 QuartzConnectionProvider
 * @author koo@weteam.me
 * @date 2014年4月18日 下午6:17:23
 *
 */
public class QuartzConnectionProvider implements ConnectionProvider {

    private static final String DB_CONFIG = "cfg.txt";

    private DruidEncryptPlugin druidPlugin;

    @Override
    public Connection getConnection() throws SQLException {
        return druidPlugin.getDataSource().getConnection();
    }

    @Override
    public void initialize() throws SQLException {
        Prop prop = PropKit.use(DB_CONFIG);
        // 默认使用ds的第一个数据库作为quart的配置数据库
        String[] ds = getDataSource(prop);
        druidPlugin = getDruidPlugin(prop, ds[0]);

        // StatFilter提供JDBC层的统计信息
        druidPlugin.addFilter(new StatFilter());
        // WallFilter的功能是防御SQL注入攻击
        WallFilter wallFilter = new WallFilter();
        wallFilter.setDbType(ds[0]);
        druidPlugin.addFilter(wallFilter);
        druidPlugin.start();
    }

    @Override
    public void shutdown() throws SQLException {
        druidPlugin.stop();
    }

    /**
     * 获取数据源
     * 
     * @return
     */
    private String[] getDataSource(Prop prop) {
        String ds = prop.get("db.ds", "");
        if (StrKit.isBlank(ds)) {
            return (new String[0]);
        }
        if (ds.contains("，")) {
            new IllegalArgumentException("Cannot use ，in ds");
        }
        return ds.split(",");
    }

    /**
     * DruidPlugin
     * 
     * @param prop
     *            ： property
     * @param ds
     * @return
     */
    private DruidEncryptPlugin getDruidPlugin(Prop prop, String ds) {
        String url = prop.get(String.format("db.%s.url", ds));
        url = String.format("jdbc:%s://%s", ds, url);
        String endsWith = "?characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull";
        if (!url.endsWith(endsWith)) {
            url += endsWith;
        }
        return new DruidEncryptPlugin(url, prop.get(String.format("db.%s.user", ds)),
                prop.get(String.format("db.%s.password", ds)));
    }

}
